<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-list', title: '盘点明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">基础信息</div>
          <customFormItem label="业务单号" name="busKey" :parent="_self" :form="form" help='自动设置' disabled/>
          <customFormItem
            label="盘点仓库" name="warehouseName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.warehouse(selectChange)"
            :disabled="!propParent.cpFormNew"
          />

          <div class="label-class">
            <strong>日期/操作人</strong>{{form.gmtCreate}}/{{form.busUser}}
          </div>

          <customFormItem label="盘点类型" name="checkType" :parent="_self" :form="form"
          :type="constCommon.formItemType.selectStatic.name"
          :clearable="false"
          :config="{ options: checkTypeList }" :disabled="!propParent.cpFormNew" />

          <customFormItem
            label="库位" name="locationName" :parent="_self" :form="form"
            :showSelectIcon="true"
            @focus="utilSelect.location(selectChange, form.warehouseId ? form.warehouseId : -1)"
            :disabled="!propParent.cpFormNew"
          />

          <customFormItem
            label="商品名称" name="matrName" :parent="_self" :form="form"
            :showSelectIcon="true"
            @focus="utilSelect.matr(selectChange)"
            :disabled="!propParent.cpFormNew"
          />

          <div class="label-class">
            <strong>理论库存</strong>{{form.stockNum}}
            <p style="display: inline-block;font-size: 12px;" v-show="form.stockNum">
              (
                <span style="color: #1a4fd2;margin-right: 8px;">正常: {{form.stockNormal}}</span>
              <span style="color: red;margin-right: 8px;">盘盈: {{form.stockSurplus}}</span>
              <span style="color: green;margin-right: 8px;">盘亏: {{form.stockLoss}}</span>
              <span style="color: gray;">未盘: {{form.stockUnknown}}</span>
              )
            </p>
          </div>

        </template>
      </customForm>
      <div id="box-list" class="box-title">盘点明细</div>
      <FortenScan
          v-show="!propParent.cpFormNew"
          ref="txtScan"
          propPlaceholder="扫描SN/RFID"
          @after-scan="barCodeScan"
          propType="uniqueCode"
          style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px"
        />
      <data-view
        propViewKey="wm_stock_check_item"
        :propInitData="form"
        ref="childDataView"
        :propNoEditRow="true"
        :propHideQueryButton="true"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propIsTdesign="true"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
      />

    </div>
  </div>
</template>

<script>
import barcodeParse from '@/util/barcodeParse.js'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      checkTypeList: [
        {
          value: 'all',
          label: '所有库存',
        },
        {
          value: 'today',
          label: '今天库存变动库存',
        },
        {
          value: 'yesterday',
          label: '昨天库存变动库存',
        },
        {
          value: 'thisWeek',
          label: '本周库存变动库存',
        },
        {
          value: 'thisMonth',
          label: '本月库存变动库存',
        },
        {
          value: 'lastMonth',
          label: '上月库存变动库存',
        }
      ],
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: callback => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        let warehouseName = this.propDictionaries.warehouseId.filter(wh => this.form.warehouseId == wh.id).map(wh => wh.name)[0]
        this.$set(this.form, 'warehouseName', warehouseName)
        // this.$set(this.form, 'flagFinished', 0)
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          this.addNewInit()
        }

        this.loadDtl()

        //结束盘点的不允许删除
        that.propParent.setButtonInvisible('viewForm', 'vfb-delete', this.strings.isNotBlank(this.form.id) && this.form.flagFinished)
      },
      afterSave: () => {
        that.propParent.ocRefreshCurrentRow()
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'finishCheck') {
          that.$confirm('是否结束盘点?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.form.flagFinished = true
            that.propParent.ocAsynSaveViewForm()
          }).catch(() => {
          })
        } else  if (buttonKey == 'begin') {
          that.propParent.ocAsynSaveViewForm()
        }
      }
    })
  },

  computed: {
    // 是否有明细
    cpHasDtl() {
      return this.form.countDtl > 0
    },
  },
  methods: {
    // 商品 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },

    selectChange(row, refName) {
      // 盘点仓库 选择
      if (refName == 'tableDrawerWarehouse') {
        this.$set(this.form, 'warehouseName', row.warehouseName)
        this.$set(this.form, 'warehouseId', row.warehouseId)
      }
       // 库位 选择
      if (refName == 'tableDrawerLocation') {
        this.$set(this.form, 'locationId', row.id)
        this.$set(this.form, 'locationName', row.name)
        this.$set(this.form, 'matrId', null)
        this.$set(this.form, 'matrName', null)
       }
       // 商品名称 选择
      if (refName == 'tableDrawerMatr') {
        this.$set(this.form, 'matrName', row.matrName)
        this.$set(this.form, 'matrId', row.matrId)
      }

    },

    loadDtl() {
      if (!this.$refs.childDataView) {
        return
      }
      let $newWrapper = this.$newWrapper()
      if (this.form.id) {
        $newWrapper.eq('checkId', this.form.id)
      } else {
        $newWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper($newWrapper)
    },

    async barCodeScan(txtScan) {
      if (Object.prototype.toString.call(this.form.warehouseId) !== '[object String]' || this.form.warehouseId == '') {
        this.utilMessage.error('请先选择盘点仓库')
        return
      }
      let codeType = barcodeParse.barCodeType(txtScan)
      if (codeType == 'SN' || codeType == 'RFID') {
        this.utilVue.loadShow(true)
        this.$ajax.get(`/wm/stock_check/scan?uc=${txtScan}&checkId=${this.form.id}`).then(resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            const data =  resp.data
            this.$set(this.form, 'stockNum', data.stockNum)
            this.$set(this.form, 'stockNormal', data.stockNormal)
            this.$set(this.form, 'stockSurplus', data.stockSurplus)
            this.$set(this.form, 'stockUnknown', data.stockUnknown)
            this.$set(this.form, 'stockLoss', data.stockLoss)
            this.$refs.txtScan.focus()
            this.utilVue.loadHide()
            this.loadDtl()
          }
        })
      } else {
        this.utilMessage.error('不正确的SN/RFID')
      }
    },

    saveCheckItem(stock) {
      this.$ajax.post('/wm/stock_check_item/save', stock).then(resp => {
        if (resp.code == 0) {
          this.loadDtl()
        }
      })
    },
    async saveCheck(stock) { //保存盘点记录
      if (!this.form.id || this.form.id == null) {
        let warehouseName = this.propDictionaries.warehouseId.filter(wh => this.form.warehouseId == wh.id).map(wh => wh.name)[0]
        this.$set(this.form, 'warehouseName', warehouseName)
        await this.propParent.ocAsynSaveViewForm()
        stock.checkId = this.form.id
        this.saveCheckItem(stock)
      } else {
        this.saveCheckItem(stock)
      }
    },

    addNewInit() {
      this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
      this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().id)
      this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
      this.$set(this.form, 'gmtCreate', new Date().format(this.dates.defaultDatePattern))
      this.form.stockNum = 0
      this.form.stockSurplus = 0
      this.form.stockUnknown = 0
      this.form.stockLoss = 0
      this.form.stockNormal = 0
    },

  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {customAnchor},
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
